var tools = "";

var pagePath = path;
var resourcePath = $("#resourcePath").val();

$(function(){
	var col=[
		{title:tableOpt.getCheckBox(null),name:"ID",width:"",align:"center",format:function(json){return tableOpt.getCheckBox(json.ID)}},
		{title:"任务名称",name:"TASKNAME",width:"10%",align:"center"},
		{title:"管道名称",name:"LINENAME",width:"15%",align:"center"},
		{title:"发球点",name:"FROMPIG",width:"10%",align:"center"},
		{title:"收球点",name:"TOPIG",width:"10%",align:"center"},
		{title:"计划清管时间",name:"PLANPAGDATETIME",width:"15%",align:"center"},
		{title:"创建人",name:"CREATEUSER",width:"10%",align:"center"},
		{title:"状态",name:"STAUS",width:"10%",align:"center",format:function(json){ return tableOpt.getState(json.STAUS)}},
		{title:"编辑",name:"ID",width:"5%",align:"center",format:function(json){return tableOpt.getAdd(json.ID)}},
		{title:"发布",name:"ID",width:"5%",align:"center",format:function(json){return tableOpt.getPublish(json.ID)}},
		{title:"附件",name:"ID",width:"5%",align:"center",format:function(json){return tableOpt.getDownload(json.ID)}}
	];



	new page(".container-fluid:eq(1)",col,undefined,undefined,function(){
		$(".tabBox table td").css("border","0px ");
		$(".tabBox table th").css("border","0px ")
	});



	//init();
})

function addStateCss(){
	var t = $("#dataTable").find("tr[dname='dataRow_']");
	for (var i = 0; i < t.length; i++) {
		var tdrow = t.eq(i).find("td");
		for (var j = 0; j < tdrow.length; j++) {
			if(tdrow.eq(j).children().html() == "已发布"){
				t.eq(i).find("td").css({'border-bottom': '1px solid #f4daa3','background-color':'#fffaf0'});
			}
		}
	}
}

//查询
function searchFun(){
	var lineId =  $('#JQ_pipeline').select3().val();
	var fromValId = $('#JQ_begin').select3().val();
	var toValId =$('#JQ_end').select3().val();
	var data = {"taskName":$.trim($("#taskName").val()),"lineId":lineId,"fromValId":fromValId,"toValId":toValId};
	$('#dataTable').selectDataAfterSetParm(data);
}

var tableOpt = {


	getCheckBox:function(id){
		var name = null == id ? 'checkAll' : 'checkSingle';
		var html = "<li style='list-style-type:none;' class='w5'><span class='table-ck'>" +
			"<span id='"+id+"' name='"+name+"' class='check-box selected' onclick=''><i></i>" +
			"</span></span></li>";
		return html;

	},

	getState:function(data){
		if("1" == data){
			return "未发布";
		}else if("2" == data){
			return "<p style='color:#FFAD00 !important'>已发布</p>";
		}
	},

	getAdd:function(data){
		var html = "<li style='list-style-type:none;' class='w-q65'><a href='javascript:void(0);' class='edit_00' onclick='getAddOrModify(\""+data+"\");'></a></li>";

		return html;
	},
	getPublish:function(data){
		var html = "<li style='list-style-type:none;' class='w-q65'><a href='javascript:void(0);'  class='public_00' onclick='publishFun(\""+data+"\");'></a></li>";
		return html;
	},
	getDownload:function(data){
		var html = "<li style='list-style-type:none;' class='w-q65'><a href='javascript:void(0);' class='download_00' onclick='downloadTaskFile(\""+data+"\");'></a></li>";
		return html;
	},
}


/* 日期格式化 */
Date.prototype.Format = function(fmt) {
    var o = {
        "M+" : this.getMonth() + 1, //月份
        "d+" : this.getDate(), //日
        "h+" : this.getHours(), //小时
        "m+" : this.getMinutes(), //分
        "s+" : this.getSeconds(), //秒
        "q+" : Math.floor((this.getMonth() + 3) / 3), //季度
        "S" : this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")
                .substr(4 - RegExp.$1.length));
    for ( var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1,
                    (RegExp.$1.length == 1) ? (o[k])
                            : (("00" + o[k])
                            .substr(("" + o[k]).length)));
    return fmt;
}

//删除
function deleteFun(ids){
	var pagePath = path;
	//获取所有name = childSelect的input
	var childBox = $("span[name=checkSingle]");
	if(ids == "mutiCheck"){
		var idsArr = new Array();
		var count = 0;
		for(var i= 0 ; i < childBox.length;i ++){
			if(childBox.eq(i).children().hasClass("active")){
				idsArr.push(childBox[i].id);
				count++;
			}
		}
		if(idsArr.length < 1){
			$(this).MSG({content:'请先勾选需要删除的任务!'});
			return ;
		}
		var idStr = idsArr.join();
		$(this).MSG({
			type: 'confirm',
			yesBtnTxt: '确定',
			height: 230,
			content: '请确认是否删除任务？',
			yesBtnAct: function(){
				var url = pagePath + "/pig/cleanPipeLineManager/deleteFun.json?idStr="+idStr;
				$().invoke(url,{},[function(m,r){
					var delCount = r.delCount;
					var undelTask = r.undelTask;
					if(0 == delCount && "" != undelTask){
						$(this).MSG({
							type: 'error',
							content: '删除失败，已发布的任务不能删除！',
						});
					}
					if(0 < delCount && "" == undelTask){
						$(this).MSG({
							type: 'success',
							content: '成功删除！',
						});
						$(".tabBox").refresh();
					}
					if(0 < delCount && "" != undelTask){
						$(this).MSG({
							type: 'success',
							content: '已发布的任务不可删除，其他任务已成功删除！',
						});
						$(".tabBox").refresh();
					}
				}]);
			}
		});

	}else{
		$(this).MSG({
			type: 'confirm',
			yesBtnTxt: '确定',
			height: 230,
			content: '请确认是否删除该任务？',
			yesBtnAct: function(){
				var url = pagePath + "/pig/cleanPipeLineManager/deleteFun.json?idStr="+ids;
				$().invoke(url,{},[function(m,r){
					if(r == 0){
						$(this).MSG({
							type: 'error',
							content: '删除失败，已发布的任务不能删除！',
						});
					}else{
						$(this).MSG({
							type: 'success',
							content: '成功删除！',

						});
						$(".tabBox").refresh();
					}
				}]);

			}
		});

	}
}

//发布
function publishFun(ids){
	var pagePath = path;
	var childBox = $("span[name=checkSingle]");
	var count = 0;
	if(ids == "mutiCheck"){
		var idsArr = new Array();
		for(var i= 0 ; i< childBox.length ;i ++){
			if(childBox.eq(i).children().hasClass("active")){
				idsArr.push(childBox[i].id);
				count ++;
			}
		}
		if(idsArr.length < 1){
			$(this).MSG({content:'请先勾选需要发布的任务!'});
			return ;
		}
		var idStr = idsArr.join();
		$(this).MSG({
			type: 'confirm',
			yesBtnTxt: '确定',
			height: 230,
			content: '请确认是否发布任务？',
			yesBtnAct: function(){
				var url = pagePath + "/pig/cleanPipeLineManager/publishFun.json?idStr="+idStr;
				$().invoke(url,{},[function(m,r){
					if(r == 0){
						$(this).MSG({
							type: 'error',
							content: '发布失败，该任务已发布！',
						});
					}else if(r < idsArr.length)
					{
						$(this).MSG({
							type: 'success',
							content: "已发布的任务不可再次发布，其他任务已成功发布！",
						});
						$(".tabBox").refresh();
					}else if(r ==idsArr.length){
						$(this).MSG({
							type: 'success',
							content: "发布成功！",
						});
						$(".tabBox").refresh();
					}

				}]);
			}
		});

	}else{
		$(this).MSG({
			type: 'confirm',
			yesBtnTxt: '确定',
			height: 230,
			content: '请确认是否发布任务？',
			yesBtnAct: function(){
				var url = pagePath + "/pig/cleanPipeLineManager/publishFun.json?idStr="+ids;
				$().invoke(url,{},[function(m,r){
					if(r == 0){
						$(this).MSG({
							type: 'error',
							content: '发布失败，该任务已发布！',
						});
					}else{
						$(this).MSG({
							type: 'success',
							content: "发布成功！",
						});
						$("#"+ids).parent().parent().parent().parent().find("td:eq(7)").html("<p style='color:#FFAD00 !important'>已发布</p>");
						$("#"+ids).parent().parent().parent().parent().find("td").css({'border-bottom': '1px solid #f4daa3','background-color':'#fffaf0'});
						$(".tabBox").refresh();
					}

				}]);
			}
		});
	}

}

//获取检测管段
function getInspSegment(lineId){
	$("#inspSegment").html('');
	var pagePath = path;
	var url = pagePath + "/pig/cleanPipeLineManager/getInspSegment.json";
	$().invoke(url,{"lineId":lineId},[function(m,r){
		var inspSegment = r;
		var html='';
		$.each(inspSegment,function(i,evalue){
			html += "<li><a href='javascript:void(0);' id='"+ evalue.id+"'>"+ evalue.name+"</a></li>";
		});
		$("#segmentDiv").html("<a href='javascript:void(0);' id='jcgdmc'>管段名称</a><span></span>");
		$("#inspSegment").html(html);
	}]);
}

/**
 * 新增或修改
 * 2015-11-19
 */
function getAddOrModify(obj){
	var pagePath = path;
	var childBox = $("span[name=checkSingle]").children();
	var count = 0;
	var taskId = "";
	//未发布状态
	var status = false;
	//是否允许修改
	var isModify = false;
	var url0 = pagePath + "/pig/cleanPipeLineManager/getTask.json";
	
	if( obj == "add"){
		window.location.href = pagePath + "/pig/cleanPipeLineManager/addOrModify.html";
	}else{
		taskId = obj;
		$().invoke(url0,{"taskId":taskId},[function(m,r){
			var st = r.staus;
			if(st != 1){
				status = true;
			}
		}],{async:false});
		if(status){
			$(this).MSG({content:'该任务已发布，不能修改!'});
			return;
		}else{
			window.location.href = pagePath + "/pig/cleanPipeLineManager/addOrModify.html?taskId="+taskId;
		}
	}
}

/**
 * 
 * @Title: copyTask   
 * @Description: 复制任务
 * @param:       
 * @return: void      
 * @throws
 */
function copyTask(){
	var pagePath = path;
	var childBox = $("span[name=checkSingle]");
	var count = 0;
	var taskId = "";
	
	for(var i= 0 ; i < childBox.length;i ++){
		if(childBox.eq(i).children().hasClass("active")){
			if(count == 0){
				taskId = childBox[i].attributes.id.value;
			}
			count++;
		}
	}
	if(count != 1){
		alert("请勾选一条数据进行操作");
		return;
	}else{
    	var url =pagePath+ "/pig/cleanPipeLineManager/copyTask.json";
    	$().invoke(url,{"taskId":taskId},[function(m,r){
			if("1" == r.copyCode){
				alert("该任务不能复制");
			}else{
				var task = r.pt;
				var line = r.pl;
				var segment = r.ps;
				var flag = r.f;
				var type = r.type;
				var pig = r.pigg;
				var cta = r.cta;
				var ct = r.ct;
				var ctId = r.ctId;
				if(null != task && undefined != task){
					$("#copyTaskName").val(task.name);
					$("#copyTaskId").val(task.id);
				}
				if(null != line && undefined != line){
					$("#copyPipeLine").html(line.name);
				}
				if(null != segment && undefined != segment){
					$("#copyPipeSegment").html(segment.inspSegmentName);
				}
				if(null != flag && undefined != flag && null != cta && undefined != cta){
					var toolShowHtml = "";
					$("#toolShow").html("");
					if(flag){
						var html = "";
						toolShowHtml += "<div class='sel w410 clearFix' style='margin-top:11px;width:100%;'>" +
								"<div class='dropdown-list' style='float:left;width:100%' >" +
								"<div class='drop-list drop-list-min' style='width:100%;height:28px;' id='copyCleanToolDiv'>" +
								"<div class='checked' style='width:91%;height:28px;'>" +
								"</div>" +
								"<span class='down-span'></span>" +
								"</div>" +
								"<ul class='select select-min none' style='width:293px;' id='copyCleanToolUl'>" +
								"</ul>" +
								"</div>" +
								"</div>";
						$("#toolShow").html(toolShowHtml);
						
						$("#copyCleanToolDiv").children("div").html("<a href='javascript:void(0);' id='"+ctId+"'>"+ct+"</a>");
//						$("#copyCleanToolUl").html("");
						$.each(cta,function(i,evalue){
							html += "<li><a href='javascript:void(0);' id='"+evalue.ID+"'>"+evalue.NAME+"</a></li>";
						});
						$("#copyCleanToolUl").html(html);
						xiala();
					}else{
						$("#toolShow").html("<input type='text' style='width:132px;float:left;' id='copyCt' value='"+ct+"'>");
					}
				}
				if(null != type && undefined != type){
//					$("#copyCleanType").html(type.name);
					$("#copyCleanType").html("<input type='hidden' value='"+type.ID+"'/>"+ type.name );
				}
				if(null != pig && undefined != pig){
					$("#copyFromPig").html(null == pig.fromValRoom || undefined == pig.fromValRoom ? "场站阀室" : pig.fromValRoom +"<input type='hidden' value='"+pig.fromPig+"'/>");
					$("#copyToPig").html(null == pig.toValRoom || undefined == pig.toValRoom ? "场站阀室" : pig.toValRoom +"<input type='hidden' value='"+pig.toPig+"'/>");
				}
				$("#copyRemark").val(task.createRemark);
				$("#copycccc").modal("show");
			}
    	}]);
	}
}

function copySave(){
	var taskId = $("#copyTaskId").val();
	var pagePath = path;
	var url = pagePath + "/pig/cleanPipeLineManager/copySave.json";
	var taskName = $.trim($("#copyTaskName").val());
	var fromPig = $("#copyFromPig").children().val();
	var toPig = $("#copyToPig").children().val();
	var cleanTool = "";
	var planTime = $("#copyPlanTime").val();
	var remark = $("#copyRemark").val();
//	var type = $("#copyCleanType").children().attr("id");
	if("" == taskName || null == taskName || undefined == taskName){
		alert("请输入任务名称");
		return ;
	}
	if(undefined == $("#copyCt").val()){
		cleanTool = $("#copyCleanToolDiv").children().children().attr("id");
	}else if(null == $("#copyCt").val() || "" == $("#copyCt").val()){
		alert("请输入清管工具");
		return;
	}else{
		cleanTool = $("#copyCt").val();
	}
	if("" == planTime || null == planTime || undefined == planTime){
		alert("请选择计划清管时间");
		return;
	}
	if("" == fromPig || null == fromPig || undefined == fromPig){
		fromPig = "";
		alert("发球点不能为空");
		return;
	}
	if("" == toPig || null == toPig || undefined == toPig){
		toPig = "";
		alert("收球点不能为空");
		return;
	}
	/*if(undefined == type || null == type || "" == type){
		alert("清管类型数据异常，请刷新页面后重试");
		return;
	}*/
	if("" != taskId && null != taskId && undefined != taskId ){
		var data = {"taskId":taskId,"remark":remark,"cleanTool":cleanTool,"taskName":taskName,"planTime":planTime,"fromPig":fromPig,"toPig":toPig};
		$().invoke(url,data,[function(m,r){
			var msgCode = r.msgCode;
			if("1" == msgCode){
				$(this).MSG({content:'任务名称已经被使用，请重新输入'});
				return; 
			}else if("ok" == msgCode){
				alert("保存成功");
				$(".tabBox").refresh();
			}
		}]);
	}
}

function xiala(){
	$(".drop-list").each(function(i){
        var $select = $(this).parent().find(".select");
        var $checked = $(this).find(".checked");
        $checked.live('click',function(){
            if($select.hasClass('none')){
                $(".dropdown-list .select").addClass("none").eq(i).removeClass('none');
                $(".drop-list .checked").removeClass('current').eq(i).addClass('current');
            }else{
                $select.addClass('none');
                $(this).removeClass('current');
            }
            return false;
        });
        $(document).on('click', function(e){
            $select.addClass('none');
            $checked.removeClass('current');
            e.stopPropagation();
        });
    });
    $(".dropdown-list .select li").live('click',function(){
        var $txt = $(this).find('a').clone();
        var $checkedBox = $(this).parents('.dropdown-list').find('.checked');
        var $hiddenInput=$checkedBox.find('input');
        //$checkedBox.html($txt);
        $checkedBox.find("a").replaceWith($txt);
        if ($hiddenInput){
            $hiddenInput.val($txt.attr("vid"));
        }
        $(this).parent().addClass('none');
        $(this).parents('.dropdown-list').find('.checked').removeClass('current');
        return false;
    });

    //将下拉列表的位置固定
    $(".more-contents,.single-content,.tab-content").scroll(function(){
        var nScrollRight = $(this)[0].scrollLeft;
        $(this).find(".dropdown-list .select").css('marginLeft',-nScrollRight+'px').addClass("none");
        $(this).find(".drop-list .checked").removeClass('current');
        $(this).find(".max-select").find(".select").css('marginLeft',-nScrollRight-146+'px');
    });
}

/**
 * 下载任务附件
 */
function downloadTaskFile(taskId){
	var url = pagePath + "/pig/cleanPipeLineManager/downloadTaskFile.json?taskId="+taskId;
	backgroundExport(url);
}

function closeAndHref(){
	$("#tan0").modal("hide");
	$(".tabBox").refresh();
}